package org.middleware.utils;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

@Component
public class PasswordEncoderUtil {

    private final PasswordEncoder passwordEncoder;

    public PasswordEncoderUtil() {
        // 可以设置加密强度，默认10，范围4-31
        this.passwordEncoder = new BCryptPasswordEncoder(12);
    }

    /**
     * 加密密码
     */
    public String encode(String rawPassword) {
        return passwordEncoder.encode(rawPassword);
    }

    /**
     * 验证密码
     */
    public boolean matches(String rawPassword, String encodedPassword) {
        return passwordEncoder.matches(rawPassword, encodedPassword);
    }

    /**
     * 检查密码强度
     * 至少8位，包含数字、字母、特殊字符
     */
    public boolean isPasswordStrong(String password) {
        if (password == null || password.length() < 12) {
            return false;
        }

        // 检查是否包含数字
        boolean hasDigit = password.matches(".*\\d.*");
        // 检查是否包含字母
        boolean hasLetter = password.matches(".*[a-zA-Z].*");
        // 检查是否包含特殊字符
        boolean hasSpecial = password.matches(".*[!@#$%^&*()_+\\-=\\[\\]{};':\"\\\\|,.<>\\/?].*");

        return hasDigit && hasLetter && hasSpecial;
    }
}
